package com.kly.sc.api.application.controller.device;

import com.fqgj.common.api.Response;
import com.fqgj.common.api.annotations.ParamsValidate;
import com.fqgj.common.utils.CollectionUtils;
import com.kly.sc.api.application.annos.SignIgnore;
import com.kly.sc.api.application.annos.VisitorAccessible;
import com.kly.sc.api.application.controller.device.request.*;
import com.kly.sc.api.application.enums.ApiResultStatus;
import com.kly.sc.api.application.helper.RequestLocalInfo;
import com.kly.sc.api.application.utils.Result;
import com.kly.sc.api.infras.app.RequestBasicInfo;
import com.kly.sc.api.infras.utils.StringUtils;
import com.kly.user.dto.*;
import com.kly.user.enums.PermissionTypeEnum;
import com.kly.user.enums.UserTokenType;
import com.kly.user.service.AuthLoginService;
import com.kly.user.service.DeviceService;
import com.kly.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/app/device")
@Slf4j
public class DeviceController {


    @Resource
    UserService userService;
    @Resource
    AuthLoginService authLoginService;
    @Resource
    DeviceService deviceService;
    /**
     * 添加设备信息
     */
    @ResponseBody
    @RequestMapping(value = "/addDeviceInfo", method = RequestMethod.POST)
    public Response addDeviceInfo(@RequestBody DeviceInfoRequest deviceInfoRequest){

        if (Objects.isNull(deviceInfoRequest)) {
            return Response.error("The parameter deviceInfo should be empty!");
        }
        if (Objects.isNull(deviceInfoRequest.getGps()) && CollectionUtils.isEmpty(deviceInfoRequest.getWifilist())) {
            return Response.error("The gps and wifi validation failed, both gps and wifi are empty!");
        }

        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        final DeviceInfoDto deviceInfoDto = DeviceInfoDto.builder().userCode(userCode).build();
        if (Objects.nonNull(deviceInfoRequest.getGps())) {
            final GpsVO gpsVo = deviceInfoRequest.getGps();
            deviceInfoDto.setGps(GpsDto.builder().state(gpsVo.getState()).city(gpsVo.getCity()).lat(gpsVo.getLat()).lng(gpsVo.getLng()).build());
        }

        if (CollectionUtils.isNotEmpty(deviceInfoRequest.getWifilist())) {
            final List<WifiVO> wifilist = deviceInfoRequest.getWifilist();
            final List<WifiDto> wifiDtos = wifilist.stream().map(o ->
                    WifiDto.builder().bssid(o.getBssid()).ssid(o.getSsid()).type(o.getType()).build()).collect(Collectors.toList());
            deviceInfoDto.setWifilist(wifiDtos);
        }


        final Response response = userService.addDeviceInfo(deviceInfoDto);
        if (Objects.nonNull(response) && response.isSuccess()) {
            return Response.ok();
        }
        return Response.error("Add device info error");

    }


    @ResponseBody
    @RequestMapping(value = "/addPushToken")
    public Response addPushToken(@Valid @RequestBody PushTokenRequest pushTokenRequest, BindingResult results){

        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        String appCode = RequestLocalInfo.getRequestBasicInfo().getAppCode();
        if (results.hasErrors()){
            return Response.error(results.getAllErrors().get(0).getDefaultMessage());
        }
        UserTokenType byCode = UserTokenType.getByCode(pushTokenRequest.getSourceType());
        if (byCode==null){
            return Response.error(ApiResultStatus.INVALID_SOURCE_TYPE);
        }
        UserAccessDto userAccessDto = new UserAccessDto();
        userAccessDto.setToken(pushTokenRequest.getToken());
        userAccessDto.setUserCode(userCode);
        authLoginService.saveToken(userAccessDto, byCode);
        return Response.ok();
    }

    @ResponseBody
    @RequestMapping(value = "/operate/permission")
    @ParamsValidate
    public Response grantPermission(@RequestBody PermissionOperationRequest permissionOperationRequest){
        final String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        if (Objects.nonNull(permissionOperationRequest)) {
            final GrantPermissionsDto grantPermissionsDto
                    = GrantPermissionsDto.builder()
                    .permissionType(PermissionTypeEnum.fromType(permissionOperationRequest.getPermissionType()))
                    .grantFlag(permissionOperationRequest.getGrantFlag()).userCode(userCode).build();
            final Response response = deviceService.grantPermissions(grantPermissionsDto);
            if (Objects.nonNull(response) && response.isSuccess()) {
                return Response.ok();
            }
        }
        return Response.error("Permission operate failed");

    }

    /**
     * 存、取ip地址
     */
    @SignIgnore
    @VisitorAccessible
    @ResponseBody
    @RequestMapping(value = "/ip", method = RequestMethod.POST)
    public Result<Boolean> ip(@RequestBody IpReq req){

        final RequestBasicInfo requestBasicInfo = RequestLocalInfo.getRequestBasicInfo();
        log.info("获取客户端IP:{}", requestBasicInfo.getIp());
        final Response<String> response = deviceService.getAndAddIp(requestBasicInfo.getIp(), req.getType());
        if (response != null && response.isSuccess()) {
            final String ip = response.getData();
            if (req.getType() == 2) {
                return Result.ok(StringUtils.isNotEmpty(ip));
            }
        }
        return Result.ok();
    }



}
